package com.itheima.health.interceptor;

import com.itheima.health.context.BaseContext;
import com.itheima.health.pojo.User;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author deng
 * @package com.itheima.health.interceptor
 * @date Created in 2024/7/16 10:18
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod){
            HttpSession session = request.getSession();
            User loginUser = (User) session.getAttribute("loginUser");
            if (loginUser==null){
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                return false;
            }
            Integer loginUserId=loginUser.getId();
            BaseContext.setCurrentId(loginUserId);
        }

        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //用完之后，移除threadLocal中的数据，防止内存泄露
        BaseContext.removeCurrentId();
    }
}
